<template>
  <div class="topIcon" v-show="isScrollTop" @click="scrollToTop()">
    <img src="./top.png" alt />
  </div>
</template>
<script type="text/ecmascript-6">
export default {
  data() {
    return {
      isScrollTop: false
    };
  },
  mounted() {
    // 监听滚动事件
    window.addEventListener(
      "scroll",
      () => {
        this.scrollTop =
          document.documentElement.scrollTop ||
          window.pageYOffset ||
          document.body.scrollTop;

        var winH = document.documentElement.clientHeight;

        if (this.scrollTop - winH > 0) {
          this.isScrollTop = true;
        } else {
          this.isScrollTop = false;
        }
      },
      true
    );
  },
  methods: {
    scrollToTop() {
      let $this = this;

      // 返回顶部动画特效
      setTimeout(function animation() {
        if ($this.scrollTop > 0) {
          setTimeout(() => {
            // 步进速度
            $this.scrollTop = $this.scrollTop - 30;
            // 返回顶部
            if (document.documentElement.scrollTop > 0) {
              document.documentElement.scrollTop = $this.scrollTop - 30;
            } else if (window.pageYOffset > 0) {
              window.pageYOffset = $this.scrollTop - 30;
            } else if (document.body.scrollTop > 0) {
              document.body.scrollTop = $this.scrollTop - 30;
            }
            animation();
          }, 1);
        }
      }, 1);
    }
  }
};
</script>

<style scoped lang="less">
.topIcon {
  width: 1.06rem;
  height: 1.06rem;
  position: fixed;
  bottom: 1.3rem;
  right: 0.4rem;
}
</style>
